package com.yjx.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yjx.mapper.SupplierMapper;
import com.yjx.mapper.UserMapper;
import com.yjx.pojo.Supplier;
import com.yjx.pojo.User;
import com.yjx.service.SupplierService;
import com.yjx.util.Md5Password;
import com.yjx.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class SupplierServiceImpl implements SupplierService {
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 分页查询供应商管理记录
     */
    @Override
    public Map<String, Object> getAllSupplierManagement(String searchKeyword, Integer pageNum, Integer pageSize, String sortField, String sortOrder) {
        // 1. 参数校验与默认值设置（避免null异常）
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
        searchKeyword = (searchKeyword == null) ? "" : searchKeyword.trim();
        // 默认排序：按创建时间降序
        if (sortField == null || sortField.trim().isEmpty()) {
            sortField = "createdAt";
        }
        if (sortOrder == null || (!"asc".equalsIgnoreCase(sortOrder) && !"desc".equalsIgnoreCase(sortOrder))) {
            sortOrder = "desc";
        }
        Page<Supplier> page = new Page<>(pageNum, pageSize);
        IPage<Supplier> supplierIPage = supplierMapper.selectSupplierByCondition(
                page,
                searchKeyword,
                sortField,
                sortOrder
        );
        Map<String, Object> result = new HashMap<>();
        result.put("supplierManagementList", supplierIPage.getRecords());
        result.put("count", supplierIPage.getTotal());
        return result;
    }

    @Override
    public Result<Void> createSupplierManagement(Supplier supplier) {
        //参数校验
        if(supplier.getSupplyQuantity()<0){
            return Result.fail("数量不能小于0",400);
        }

        if(supplier.getPartId() ==  null){
            return Result.fail("配件编号不能为空",400);
        }
        User user = userMapper.selectById(supplier.getSupplierId());
        if(user.getRoleId() != 5)
        {
            return Result.fail("该角色不是供应商",400);
        }

        // 核心修改：将 supplierManagementId 设为 null，让数据库自增
        supplier.setSupplierManagementId(null);
        // 设置创建和更新时间
        supplier.setCreatedAt(LocalDateTime.now());
        supplier.setUpdatedAt(LocalDateTime.now());
        // 插入数据库，MyBatis-Plus 会自动处理自增主键
        if(supplierMapper.insert(supplier) > 0){
            return Result.success(null);
        }
        return Result.fail("添加失败",500);
    }

    /**
     * 更新供应商管理记录
     */
    @Override
    public Result<Void> updateSupplierManagement(Supplier supplier) {
        //参数校验
        if(supplier.getSupplyQuantity()<0){
            return Result.fail("数量不能小于0",400);
        }
        if(supplier.getPartId() ==  null){
            return Result.fail("配件编号不能为空",400);
        }
        User user = userMapper.selectById(supplier.getSupplierId());
        if(user.getRoleId() != 5){
            return Result.fail("该角色不是供应商",400);
        }
        supplier.setUpdatedAt(LocalDateTime.now());
        if(supplierMapper.updateById(supplier) > 0){
            return Result.success(null);
        }
        return Result.fail("更新失败",500);
    }

    /**
     * 删除供应商管理记录，需进行密码校验
     */
    @Override
    public Result<Void> deleteSupplierManagement(Integer supplierManagementId, Integer userId, String userPasswd) {
        if (userId == null) {
            return Result.fail("用户编号不能为空", 400);
        }
        if (userPasswd == null) {
            return Result.fail("用户密码不能为空", 400);
        }
        User user = userMapper.selectById(userId);
        String password = Md5Password.generateMD5(userPasswd);
        if (!user.getUserPasswordHash().equals(password)) {
            return Result.fail("密码错误", 400);
        }
        if (supplierMapper.deleteByManagementId(supplierManagementId) > 0) {
            return Result.success(null);
        } else {
            return Result.fail("删除失败", 500);
        }
    }
}
